import cv2
import threading
import time


class Camera:
    def __init__(self, src=0, width=640, height=360):
        self.src = src
        self.width = width
        self.height = height
        self.cap = None
        self.frame = None
        self.running = False
        self.thread = None

    def start(self):
        if self.running:
            return True
        self.cap = cv2.VideoCapture(self.src)
        if not self.cap.isOpened():
            print('[camera] 打开摄像头失败')
            return False
        # 设置分辨率（可能并非所有摄像头都支持）
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, self.width)
        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, self.height)
        self.running = True
        self.thread = threading.Thread(target=self._loop, daemon=True)
        self.thread.start()
        return True

    def stop(self):
        self.running = False
        try:
            if self.thread:
                self.thread.join(timeout=1.0)
        except Exception:
            pass
        try:
            if self.cap:
                self.cap.release()
        except Exception:
            pass

    def _loop(self):
        while self.running and self.cap and self.cap.isOpened():
            ok, frame = self.cap.read()
            if ok:
                self.frame = frame
            else:
                time.sleep(0.01)

    def read(self):
        return self.frame